public class HToolsU3 implements HTools {
	
	public int h(final int[] t, int me, int you) {
		if (isEnded(t))
			if (isWinning(t, me, you))
				return Integer.MAX_VALUE;
			else
				return Integer.MIN_VALUE;
		
		int[] w = new int[5];
		int[] e = new int[5];
		for (int box = 1; box < 5; box++) {
			w[box] = winningOf(t, me, you, box);
			e[box] = emptySlots(t, box);
		}
		boolean[] d = new boolean[5];
		for (int box = 4; box > 0 && e[box] < box - 1; box--)
			d[box] = true;
		
		int h = 0;
		int weight = 1;
		for (int box = 4; box > 0; box--) {
			if (!d[box])
				h += evaluate(w[box]) * weight;
			weight *= 20;
		}
		
		return h;
	}
	
	private int evaluate(int n) {
		if (n <= 0)
			return 10 + n;
		return 20 - n;
	}
	
	private boolean isWinning(int[] t, int me, int you) {
		return t[5 * me + 1] > t[5 * you + 1];
	}
	
	private int winningOf(int[] t, int me, int you, int box) {
		return t[5 * me + t[11 + box]] - t[5 * you + t[11 + box]];
	}
	
	private boolean isEnded(int[] t) {
		return t[5 * t[10]] == 0 || isFull(t);
	}
	
	private boolean isFull(int[] t) {
		for (int box = 1; box <= 4; box++)
			if (emptySlots(t, box) != 0)
				return false;
		return true;
	}
	
	private int emptySlots(int[] t, int box) {
		return Apagos.MAX[t[11 + box]] - t[box] - t[5 + box];
	}
	
}
